import ossConfig from '../config/ali-oss'
import report from './report'
import { getStorage } from './utils'

/**
 * 32位转字节
 * @param {*} words 32位
 */
export function wordsToBytes(words) {
	const bytes = []
	for (let b = 0; b < words.length * 32; b += 8) {
		bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF)
	}
	return bytes
}

/**
 * 字符串转字节
 * @param {*} str 字符串
 */
export function stringToBytes(str) {
	const bytes = []
	for (let i = 0; i < str.length; i++) {
		bytes.push(str.charCodeAt(i))
	}
	return bytes
}

/**
 * 字符串转32位
 * @param {*} str 字符串
 */
export function stringToWords(str) {
	const words = []
	for (let c = 0, b = 0; c < str.length; c++, b += 8) {
		words[b >>> 5] |= str.charCodeAt(c) << (24 - b % 32)
	}
	return words
}

/**
 * 字节转字符串
 * @param {*} bytes 字节
 */
export function bytesToString(bytes) {
	const str = []
	for (let i = 0; i < bytes.length; i++) {
		str.push(String.fromCharCode(bytes[i]))
	}
	return str.join('')
}

/**
 * 字节转Hex
 * @param {*} bytes 字节
 */
export function bytesToHex(bytes) {
	const hex = []
	for (let i = 0; i < bytes.length; i++) {
		hex.push((bytes[i] >>> 4).toString(16))
		hex.push((bytes[i] & 0xF).toString(16))
	}
	return hex.join('')
}

/**
 * 字节转base64
 * @param {*} bytes 字节
 */
export function bytesToBase64(bytes) {
	// 浏览器btoa存在的话直接使用
	if (typeof btoa == 'function') return btoa(bytesToString(bytes))
	
	// base64编码
	const base64map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
	// base64字节
	const base64 = []
	// 溢出字节
	let overflow

	for (let i = 0; i < bytes.length; i++) {
		switch (i % 3) {
			case 0:
				base64.push(base64map.charAt(bytes[i] >>> 2))
				overflow = (bytes[i] & 0x3) << 4
				break;
			case 1:
				base64.push(base64map.charAt(overflow | (bytes[i] >>> 4)))
				overflow = (bytes[i] & 0xF) << 2
				break;
			case 2:
				base64.push(base64map.charAt(overflow | (bytes[i] >>> 6)))
				base64.push(base64map.charAt(bytes[i] & 0x3F))
				overflow = -1
		}
	}

	// 编码溢出字节
	if (overflow != undefined && overflow != -1)
		base64.push(base64map.charAt(overflow))

	// 填充=
	while (base64.length % 4 != 0) base64.push('=');

	return base64.join('')

}

/**
 * sha1算法
 * @param {*} message 数据
 * @param {*} options 配置
 */
export function sha1(message, options) {
	let m  = stringToWords(message),
	    l  = message.length * 8,
	    w  =  [],
	    H0 =  1732584193,
	    H1 = -271733879,
	    H2 = -1732584194,
	    H3 =  271733878,
	    H4 = -1009589776

	// 填充
	m[l >> 5] |= 0x80 << (24 - l % 32)
	m[((l + 64 >>> 9) << 4) + 15] = l

	for (let i = 0; i < m.length; i += 16) {
		let a = H0,
		    b = H1,
		    c = H2,
		    d = H3,
		    e = H4

		for (let j = 0; j < 80; j++) {
			if (j < 16) w[j] = m[i + j]
			else {
				let n = w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16]
				w[j] = (n << 1) | (n >>> 31)
			}
			let t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
			         j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 :
			         j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 :
			         j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 :
			                  (H1 ^ H2 ^ H3) - 899497514)
			H4 =  H3
			H3 =  H2
			H2 = (H1 << 30) | (H1 >>> 2)
			H1 =  H0
			H0 =  t
		}
		H0 += a
		H1 += b
		H2 += c
		H3 += d
		H4 += e
	}
	const digestbytes = wordsToBytes([H0, H1, H2, H3, H4])

	return options?.asBytes ? digestbytes :
	       options?.asString ? bytesToString(digestbytes) : bytesToHex(digestbytes)
}

/**
 * 哈希算法
 * @param {*} hasher 哈希器
 * @param {*} message 数据
 * @param {*} key 访问密钥
 * @param {*} options 配置
 */
export function hmac(hasher, message, key, options) {
	if (!hasher._blocksize) hasher._blocksize = 16

	// 允许任意长度的key
	key = key.length > hasher._blocksize * 4
		? hasher(key, { asBytes: true })
		: stringToBytes(key);

	// XOR keys填充
	const okey = key
	const ikey = key.slice(0)
	for (let i = 0; i < hasher._blocksize * 4; i++) {
		okey[i] ^= 0x5C
		ikey[i] ^= 0x36
	}

	// hmac字节
	const hmacbytes = hasher(
		bytesToString(okey) + hasher(bytesToString(ikey) + message, { asString: true }),
		{ asBytes: true }
	)
	return options?.asBytes ? hmacbytes :
	       	options?.asString ? bytesToString(hmacbytes) : bytesToHex(hmacbytes)
}

/**
 * base64加密
 * @param {*} text 文本
 */
export function base64Encode(text) {
	// base64编码
	const base64map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
	// 输出
	let output = ''
	let chr1, chr2, chr3, enc1, enc2, enc3, enc4
	let i = 0
	let input = ''
	text = text.replace(/\r\n/g, '\n')

	for (let n = 0; n < text.length; n++) {
		const c = text.charCodeAt(n)
		if (c < 128) {
			input += String.fromCharCode(c)
		} else if ((c > 127) && (c < 2048)) {
			input += String.fromCharCode((c >> 6) | 192)
			input += String.fromCharCode((c & 63) | 128)
		} else {
			input += String.fromCharCode((c >> 12) | 224)
			input += String.fromCharCode(((c >> 6) & 63) | 128)
			input += String.fromCharCode((c & 63) | 128)
		}
	}

	while (i < input.length) {
		chr1 = input.charCodeAt(i++)
		chr2 = input.charCodeAt(i++)
		chr3 = input.charCodeAt(i++)
		enc1 = chr1 >> 2
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)
		enc4 = chr3 & 63
		if (isNaN(chr2)) {
				enc3 = enc4 = 64
		} else if (isNaN(chr3)) {
				enc4 = 64
		}
		output = output +
			base64map.charAt(enc1) + base64map.charAt(enc2) +
			base64map.charAt(enc3) + base64map.charAt(enc4);
	}

	return output
}

/**
 * 获取oss策略
 * @param {*} maxSize 
 * @param {*} timeout 失效时间
 */
export function getPolicy(maxSize, timeout) {
	const date = new Date()
	date.setHours(date.getHours() + timeout)

	return base64Encode(
		JSON.stringify({
			// 设置该Policy的失效时间
			expiration: date.toISOString(),
			// 设置上传文件的大小限制，默认5MB
			conditions: [
				['content-length-range', 0, (maxSize || 5) * 1024 * 1024],
			],
		})
	)
}

/**
 * 获取oss签名
 * @param {*} accessKey 访问秘钥
 * @param {*} base64 base64加密数据
 */
export function getSignature(accessKey, base64) {
	return bytesToBase64(
		hmac(
			sha1,
			base64,
			accessKey,
			{ asBytes: true }
		)
	)
}

/*
 * 上传文件到阿里云
 * @param {*} filePath 文件路径
 * @param {*} callback 回调函数
 * @param {*} options 阿里云配置 directory: 上传目录 maxSize: 最大上传内存 timeout: 上传文件时Policy的失效时间
 */
export function uploadAliyun(filePath, callback, options) {
	if (!filePath || filePath.length < 9) {
		wx.showModal({
			title: '文件错误',
			content: '请重试',
			showCancel: false,
		})
		return
	}

	const {
		cdn,
		domain,
		directory,
		accessKey,
		accessKeyId,
		maxSize,
		timeout
	} = ossConfig

	// 上传路径
	const key = (options?.directory || directory) + filePath.split('/').pop()
	// oss策略
	const policy = getPolicy(options?.maxSize || maxSize, options?.timeout || timeout)
	// 上报日志
	const reportLog = (res) => {
		if (res?.data && typeof res.data === 'object') {
			res.data.statusCode = res?.statusCode
		}
		report.reportParams({
			data: {
				url: domain,
				appName: "operational-tools",
				level: res?.statusCode,
				message: res?.data || JSON.stringify(res),
				param: key,
				token: getStorage('token'),
				requestMethod: 'post',
			},
		})
	}
	wx.uploadFile({
		url: domain,
		filePath,
		name: 'file',
		formData: {
			key,
			policy,
			OSSAccessKeyId: accessKeyId,
			signature: getSignature(accessKey, policy),
			success_action_status: 200,
		},
		success: (res) => {
			if (res.statusCode === 200) {
				const tempPath = `${cdn}/${key}`
				console.log('文件路径:' + tempPath)
				callback?.(tempPath)
			} else {
				reportLog(res)
				console.log('oss上传失败', res)
				callback?.()
				wx.showToast({
					icon: 'none',
					title: '网络异常，图片识别失败！',
				})
			}
		},
		fail: (err) => {
			reportLog(err)
			err.wxaddinfo = domain
			console.log('oss上传失败', err)
			callback?.()
			wx.showToast({
				icon: 'none',
				title: '网络异常，图片识别失败！',
			})
		},
	})
}
